<template>
  <div class="login-box">
    <div class="login-card">
      <el-card class="box-card header">
        <div slot="header" class="clearfix cxx">
          <span>黑马面经运营后台</span>
        </div>
        <div>
          <el-form label-width="80px" :rules="rules" :model="form" ref="form">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="form.username"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                v-model="form.password"
                placeholder="密码"
              ></el-input>
            </el-form-item>

            <el-form-item label-width="0">
              <el-button type="primary" @click="fn" :loading="flag"
                >登录</el-button
              >
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { loginMes } from '@/api/user'
export default {
  name: 'login-page',
  components: {},
  props: {},
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^[a-z]{5,11}$/,
            message: '密码长度不能小于5位且大于11位',
            trigger: 'blur'
          }
        ]
      },
      flag: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  methods: {
    // 重置
    reset() {
      this.$refs.form.resetFields()
    },
    async fn() {
      try {
        const result = await this.$refs.form.validate()
        console.log('检验正确可以发送请求了', result)
        this.flag = true
        const res = await loginMes(this.form)
        console.log(res)
        this.$message.success('登录成功')
        this.flag = false
        this.$router.push('/')
      } catch (err) {
        console.log(err)
        if (err.response && err.response.status === 400) {
          this.$message.error('用户名或密码输入错误')
        } else {
          this.$message.error('用户名或密码输入不规范')
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.login-box {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  .header {
    text-align: center;
    color: #fff;
  }
}

::v-deep .el-card__header {
  background-color: #727cf5;
}
.login-card {
  width: 420px;
}
</style>
